package com.lion.seaman.common.tools;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class StringTools {

    public static boolean isBlank(String str) {
        if (str == null || str.trim().equals("")) {
            return true;
        }
        return false;
    }

    public static boolean isBlank(String... str) {
        for (String s : str) {
            if (isBlank(s)) {
                return true;
            }
        }
        return false;
    }

    public static String nvl(String value, String defaultValue) {
        if (isBlank(value) || value.equalsIgnoreCase("null")) {
            return defaultValue;
        }
        return value;
    }

    public static String nvl(String value) {
        return nvl(value, "");
    }

    public static String format(String pattern, Object... args) {
        return MessageFormat.format(pattern, args);
    }

    public static boolean isNumber(String text) {
        if (isBlank(text)) {
            return false;
        }
        String regex = "^(\\d+)(\\.\\d+)?$";
        return regexMatch(text, regex);
    }

    public static boolean isIntegerNumber(String text) {
        if (isBlank(text)) {
            return false;
        }
        String regex = "^\\d+$";
        return regexMatch(text, regex);
    }

    public static boolean regexMatch(String text, String regex) {
        return Pattern.compile(regex).matcher(text).find();
    }

    public static String processNullString(String str) {
        if (str == null || "null".equalsIgnoreCase(str)) {
            str = "";
        }
        return str.trim();
    }

    public static String[] split(String str, String sep) {
        List<String> list = new ArrayList<String>();
        String tmp = new String(str);
        int index;
        while ((index = tmp.indexOf(sep)) != -1) {
            list.add(tmp.substring(0, index));
            tmp = tmp.substring(++index);
        }
        if (list.isEmpty()) {
            return new String[]{str};
        } else {
            return list.toArray(new String[0]);
        }
    }

    public static <T> T coverTo(String val, T defaultValue) {
        try {
            if (defaultValue instanceof Long) {
                return (T) Long.valueOf(val);
            } else if (defaultValue instanceof Integer) {
                return (T) Integer.valueOf(val);
            } else if (defaultValue instanceof Double) {
                return (T) Double.valueOf(val);
            } else if (defaultValue instanceof Float) {
                return (T) Float.valueOf(val);
            } else if (defaultValue instanceof Boolean) {
                return (T) Boolean.valueOf(val);
            } else {
                return (T) val;
            }
        } catch (Exception e) {
        }
        return defaultValue;
    }

    public static boolean isNotBlank(String source) {
        return !isBlank(source);
    }
}
